;; just trying out my own pop3 client stuff.

(defun open-socket (host port)
  (socket-connect port host))

(defun send-line (stream line)
  "Send a line of text to the socket stream, terminating it with CR+LF."
  (princ line stream)
  (princ #\Return stream)
  (princ #\Newline stream)
  (force-output stream))

;; a string containing a new line character:
(defvar *nl* (make-string 1 :initial-element #\newline))

;; collect all input from a socket connection into a string, stopping when
;; a line from the server just contains a single period:
(defun collect-input (socket period-flag)
  (let ((ret "")
	temp)
    (loop
     (let ((line (read-line socket nil nil)))
       (unless line (return))
       (princ "Line: ") (princ line) (terpri)
       (if (equal line ".") (return)) ;; nntp server terminates response with a period crlf
       (if (null period-flag) (return))
       (setq ret (concatenate 'string ret line *nl*))
       (if (search "-ERR" line) (return))))
    ret))

(defun send-command-print-response (stream command period-flag)
  (terpri)
  (princ "Sending: ")
  (princ command)
  (terpri)
  (send-line stream command)
  (terpri)
  (collect-input stream period-flag))
    
(defun test (server user passwd &aux (ret nil))
  ;; Open connection
  (let ((socket (open-socket server 110)))
    (unwind-protect
	(progn
	  (send-command-print-response socket (concatenate 'string "USER " user) nil)
	  (send-command-print-response socket (concatenate 'string "PASS " passwd) nil)
	  (send-command-print-response socket "STAT" nil)
	  (let* ((response
		  (send-command-print-response socket "LIST" t))
		 (index1 (search "+OK " response)))
	    ;;(print (list "**** response = " response "  index1 = " index1))
	    ;; the string between index1 and index2 will contain the number of email messages
	    ;; available to be read:
	    (if index1
		(let ((index2 (search " " response :start2 (+ index1 4))))
		  ;;(print (list "**** index2 = " index2))
		  (if index2
		      (let ((count (read-from-string (subseq response (+ index1 4) index2))))
			(print (list "**** count = " count))
			(dotimes (i count)
			  (setq ret
				(cons
				 (send-command-print-response
				  socket
				  (concatenate 'string "RETR " (princ-to-string (1+ i))) t)
				 ret))
			  ;; uncomment the following line if you want to delete the messages on the server:
			  ;;(send-command-print-response socket "DELE 1" nil)
			  ))))))
	  (send-command-print-response socket "QUIT" nil))
      ;; Close socket before exiting.
      (close socket)))
  (reverse ret))



